<template>
  <div class="travel-management">
    <h2 class="title">旅游管理</h2>
    <div class="toolbar">
      <el-input
          v-model="searchQuery"
          placeholder="搜索旅游名称"
          style="width: 200px; margin-right: 10px;"
          @input="fetchTravels"
      />
      <el-button type="primary" @click="openAddDialog">添加旅游</el-button>
    </div>
    <el-table :data="travels" style="width: 100%">
      <el-table-column prop="tripName" label="旅游名称"></el-table-column>
      <el-table-column prop="totalCost" label="总花销"></el-table-column>
      <el-table-column prop="startDate" label="开始日期" ></el-table-column>
      <el-table-column prop="endDate" label="结束日期" ></el-table-column>
      <el-table-column prop="createdAt" label="创建时间" ></el-table-column>
      <el-table-column prop="updatedAt" label="修改时间" ></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="editTravel(scope.row.id)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteTravel(scope.row.id)">删除</el-button>
          <el-button size="mini" @click="showDetails(scope.row.id)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="page"
        @current-change="fetchTravels"
    ></el-pagination>

    <!-- 添加/编辑旅游对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="添加/编辑旅游" width="50%" @close="handleDialogClose">
      <el-form :model="newTravel" :rules="rules" ref="travelForm" class="travel-form" label-width="120px">
        <el-form-item label="旅游名称" prop="tripName">
          <el-input v-model="newTravel.tripName"></el-input>
        </el-form-item>
        <el-form-item label="总花销" prop="totalCost">
          <el-input v-model.number="newTravel.totalCost" disabled></el-input> <!-- Total cost is disabled -->
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker v-model="newTravel.startDate" type="datetime" placeholder="选择开始日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker v-model="newTravel.endDate" type="datetime" placeholder="选择结束日期"></el-date-picker>
        </el-form-item>
        <el-divider>详细信息</el-divider>
        <div v-for="(detail, index) in newTravel.travelDetailsRequests" :key="index" class="detail-item">
          <el-form-item label="子行程名称" :prop="'travelDetailsRequests.' + index + '.subTripName'">
            <el-input v-model="detail.subTripName"></el-input>
          </el-form-item>
          <el-form-item label="出发地" :prop="'travelDetailsRequests.' + index + '.departure'">
            <el-input v-model="detail.departure"></el-input>
          </el-form-item>
          <el-form-item label="目的地" :prop="'travelDetailsRequests.' + index + '.destination'">
            <el-input v-model="detail.destination"></el-input>
          </el-form-item>
          <el-form-item label="花销金额" :prop="'travelDetailsRequests.' + index + '.cost'">
            <el-input v-model.number="detail.cost" @change="updateTotalCost"></el-input>
          </el-form-item>
          <el-form-item label="花销明细" :prop="'travelDetailsRequests.' + index + '.costDetails'">
            <el-input v-model="detail.costDetails"></el-input>
          </el-form-item>
          <el-button type="danger" @click="removeDetail(index)" class="remove-detail-button">删除</el-button>
          <el-divider></el-divider>
        </div>
        <el-button type="primary" @click="addDetail" class="add-detail-button">添加行程</el-button>
        <el-form-item>
          <el-button type="primary" @click="validateForm">{{ isEditing ? '更新' : '添加' }}</el-button>
          <el-button @click="resetForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog :visible.sync="detailsDialogVisible" title="旅游详情" width="50%">
      <el-form :model="detailsTravel" label-width="120px" class="travel-form">
        <el-form-item label="旅游名称">
          <el-input :value="detailsTravel.tripName" disabled></el-input>
        </el-form-item>
        <el-form-item label="总花销">
          <el-input :value="detailsTravel.totalCost" disabled></el-input>
        </el-form-item>
        <el-form-item label="开始日期">
          <el-input :value="detailsTravel.startDate" disabled></el-input>
        </el-form-item>
        <el-form-item label="结束日期">
          <el-input :value="detailsTravel.startDate" disabled></el-input>
        </el-form-item>
        <el-divider>详细信息</el-divider>
        <div v-for="(detail, index) in detailsTravel.travelDetailsRequests" :key="index">
          <el-form-item label="子行程名称">
            <el-input :value="detail.subTripName" disabled></el-input>
          </el-form-item>
          <el-form-item label="出发地">
            <el-input :value="detail.departure" disabled></el-input>
          </el-form-item>
          <el-form-item label="目的地">
            <el-input :value="detail.destination" disabled></el-input>
          </el-form-item>
          <el-form-item label="花销金额">
            <el-input :value="detail.cost" disabled></el-input>
          </el-form-item>
          <el-form-item label="花销明细">
            <el-input :value="detail.costDetails" disabled></el-input>
          </el-form-item>
          <el-divider></el-divider>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { Message, MessageBox } from 'element-ui';

export default {
  name: 'TravelManagement',
  data() {
    return {
      travels: [],
      searchQuery: '',
      newTravel: {
        id: '',
        tripName: '',
        totalCost: 0,
        startDate: null,
        endDate: null,
        travelDetailsRequests: [],
        createdAt: '',
        updatedAt: ''
      },
      detailsTravel: {
        id: '',
        tripName: '',
        totalCost: 0,
        startDate: null,
        endDate: null,
        travelDetailsRequests: [],
        createdAt: '',
        updatedAt: ''
      },
      isEditing: false,
      total: 0,
      page: 1,
      pageSize: 10,
      dialogVisible: false,
      detailsDialogVisible: false,
      rules: {
        tripName: [{ required: true, message: '请输入旅游名称', trigger: 'blur' }],
        totalCost: [{ required: true, type: 'number', message: '请输入总花销', trigger: 'blur' }],
        startDate: [{ required: true, type: 'date', message: '请选择开始日期', trigger: 'change' }],
        endDate: [{ required: true, type: 'date', message: '请选择结束日期', trigger: 'change' }],
        travelDetailsRequests: {
          type: 'array',
          required: true,
          defaultField: {
            type: 'object',
            fields: {
              subTripName: { required: true, message: '请输入子行程名称', trigger: 'blur' },
              departure: { required: true, message: '请输入出发地', trigger: 'blur' },
              destination: { required: true, message: '请输入目的地', trigger: 'blur' },
              cost: { type: 'number', message: '请输入花销金额', trigger: 'blur' }
            }
          }
        }
      }
    };
  },
  created() {
    this.fetchTravels();
  },
  methods: {
    fetchTravels() {
      axios.get('/travel/list', {
        params: {
          page: this.page,
          pageSize: this.pageSize,
          tripName: this.searchQuery
        }
      })
          .then(response => {
            this.travels = response.data.data.rows;
            this.total = response.data.data.total;
          })
          .catch(error => {
            console.error('Error fetching travels:', error);
          });
    },
    addTravel() {
      axios.post('/travel/add', this.newTravel)
          .then(response => {
            if (response.data.code === 200) {
              this.fetchTravels();
              this.resetForm();
              Message.success('添加成功');
            } else {
              Message.error(response.data.msg);
            }
          })
          .catch(error => {
            console.error('Error adding travel:', error);
          });
    },
    editTravel(id) {
      axios.get(`/travel/get/${id}`)
          .then(response => {
            if (response.data.code === 200) {
              const travel = response.data.data;
              this.newTravel = {
                ...travel,
                travelDetailsRequests: Array.isArray(travel.travelDetailsRequests) ? [...travel.travelDetailsRequests] : []
              };
              this.isEditing = true;
              this.dialogVisible = true;
              this.updateTotalCost(); // Recalculate total cost on edit
            } else {
              Message.error(response.data.msg);
            }
          })
          .catch(error => {
            console.error('Error fetching travel details:', error);
          });
    },
    updateTravel() {
      axios.put('/travel/update', this.newTravel)
          .then(response => {
            if (response.data.code === 200) {
              this.fetchTravels();
              this.resetForm();
              Message.success('更新成功');
            } else {
              Message.error(response.data.msg);
            }
          })
          .catch(error => {
            console.error('Error updating travel:', error);
          });
    },
    confirmDelete(id) {
      MessageBox.confirm('确定删除此旅游记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteTravel(id);
      }).catch(() => {
        Message.info('已取消删除');
      });
    },
    deleteTravel(id) {
      axios.delete(`/travel/delete/${id}`)
          .then(response => {
            if (response.data.code === 200) {
              this.fetchTravels();
              Message.success('删除成功');
            } else {
              Message.error(response.data.msg);
            }
          })
          .catch(error => {
            console.error('Error deleting travel:', error);
          });
    },
    resetForm() {
      this.newTravel = {
        id: '',
        tripName: '',
        totalCost: 0,
        startDate: null,
        endDate: null,
        travelDetailsRequests: [],
        createdAt: '',
        updatedAt: ''
      };
      this.isEditing = false;
      this.dialogVisible = false;
    },
    handleDialogClose() {
      this.resetForm();
    },
    openAddDialog() {
      this.resetForm();
      this.isEditing = false;
      this.dialogVisible = true;
    },
    validateForm() {
      this.$refs.travelForm.validate((valid) => {
        if (valid) {
          this.isEditing ? this.updateTravel() : this.addTravel();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    addDetail() {
      if (!this.newTravel.travelDetailsRequests) {
        this.$set(this.newTravel, 'travelDetailsRequests', []);
      }
      this.newTravel.travelDetailsRequests.push({
        subTripName: '',
        departure: '',
        destination: '',
        cost: null,
        costDetails: ''
      });
    },
    removeDetail(index) {
      this.newTravel.travelDetailsRequests.splice(index, 1);
      this.updateTotalCost(); // Recalculate total cost on detail removal
    },
    updateTotalCost() {
      const totalCost = this.newTravel.travelDetailsRequests.reduce((sum, detail) => sum + (detail.cost || 0), 0);
      this.newTravel.totalCost = totalCost;
    },
    showDetails(id) {
      axios.get(`/travel/get/${id}`)
          .then(response => {
            if (response.data.code === 200) {
              const travel = response.data.data;
              this.detailsTravel = {
                ...travel,
                travelDetailsRequests: Array.isArray(travel.travelDetailsRequests) ? [...travel.travelDetailsRequests] : []
              };
              this.detailsDialogVisible = true;
            } else {
              Message.error(response.data.msg);
            }
          })
          .catch(error => {
            console.error('Error fetching travel details:', error);
          });
    }
  }
};
</script>

<style scoped>
.travel-management {
  height: 100vh;
  overflow: hidden;
  background-image: url('../assets/pdx.png'); /* Ensure the path is correct */
  background-size: cover;
  background-position: center;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  padding: 20px;
}

.title {
  color: black;
  margin-top: 20px;
}

.toolbar {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  margin-bottom: 20px;
}

.travel-form {
  width: 100%;
  margin-bottom: 20px;
}

.el-form-item {
  margin-bottom: 10px;
}

.detail-item {
  border: 1px solid #ddd;
  padding: 10px;
  margin-bottom: 20px; /* Increase bottom margin */
  border-radius: 4px;
  background-color: #f9f9f9;
}

.add-detail-button {
  margin-bottom: 20px; /* Add margin to button */
}

.remove-detail-button {
  margin-top: 10px; /* Add margin to button */
}
</style>


